package com.ebt.m.proposal_v2.helper;

import android.content.res.Resources;
import android.os.Build;
import android.os.Handler;
import android.webkit.WebView;

import com.ebt.m.proposal_v2.interfaces.OnJavaScriptCallback;

/**
 * WebView交互
 *
 * @author archer.qi
 *         Created on 2017/6/2.
 */
public class WebViewCallback {
    private WebView mWebView;
    private String mTag;
    private int id;

    public WebViewCallback with(WebView webView) {
        mWebView = webView;
        return this;
    }

    public void without() {
        mWebView = null;
    }

    public WebViewCallback setTag(String tag) {
        mTag = tag;
        return this;
    }

    public String getTag() {
        return mTag;
    }

    public WebViewCallback setId(int id) {
        this.id = id;
        return this;
    }

    public int getId() {
        return id;
    }

    /**
     * 添加Js调用Native接口
     *
     * @param nativeApi
     * @param jsInstanceName
     * @param <T>
     * @return
     */
    public <T extends NativeAPI> WebViewCallback addNativeInterface(T nativeApi, String jsInstanceName) {
        if (mWebView == null) {
            throw new Resources.NotFoundException("WebView not found, please set a WebView by with()");
        }
        mWebView.addJavascriptInterface(nativeApi, jsInstanceName);
        return this;
    }

    /**
     * 添加Native调用Js接口（请在UI线程调用）
     *
     * @param jsMethod 完整方法名，包括参数；如 getUser() / getUserById()
     * @return
     */
    public WebViewCallback addJsInterface(String jsMethod, OnJavaScriptCallback callback) {
        if (mWebView == null) {
            throw new Resources.NotFoundException("WebView not found, please set a WebView by with()");
        }
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            mWebView.evaluateJavascript(jsMethod, responseJson -> {
                if (callback != null) {
                    callback.onCallResponse(responseJson);
                }
            });
        } else {
            mWebView.loadUrl("javascript:" + jsMethod);
            new Handler().postDelayed(() -> {
                NativeAPI.JSResponse jsResponse = NativeAPI.getJavascriptCallResponse();
                if (jsResponse == null || !jsMethod.contains(jsResponse.methodName)) {
                    if (callback != null) {
                        callback.onCallResponse(null);
                    }
                } else {
                    if (callback != null) {
                        callback.onCallResponse(jsResponse.response);
                    }
                }
            }, 150);
        }
        return this;
    }

}
